package action;

import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import proxy.ProxyFactory;
import queryterm.CourierQuery;
import service.CourierService;
import service.CourierServiceInterface;
import utils.PageBean;


import beans.Agent;
import beans.Branch;
import beans.Card;
import beans.Company;
import beans.Courier;
import beans.Express;
import beans.HibernateSessionFactory;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import dao.CardDao;
import dao.CompanyDao;
import dao.CourierDao;
import dao.ExpressDao;
import dao.QueryDAO;

@SuppressWarnings("serial")
public class CourierAction extends ActionSupport implements ModelDriven<Courier>{
	private List<Courier> couriers;
	private List<Express> expressBranchs;
	private List<Company> companies;
	private List<Branch> branchs;
	private List<Card> cards;

	CourierDao courierDao = new CourierDao();
	CompanyDao companyDao = new CompanyDao();
	ExpressDao expressBranchDao = new ExpressDao();
	QueryDAO queryDAO = new QueryDAO();

	private Courier courier = new Courier();
	private CardDao cardDao = new CardDao();
	
	private int rows;// easyui页大小
    private int page;// easyui当前页
    private String ids;//删除id集合
    
    private String returnType;// 返回类型
    private String pageName;//返回页面
    
    private Map<String, Object> courierMap;

	private int courierID;
	private int cardID;
	private int company = 0;
	private int branch;
	private int expressId;
	private int curpage; // 当前页
	private int pageSize; // 页大小
	private String sernum;
	private String flag;
	private String value;
	private PageBean<Courier> courierPage;
	private CourierQuery courierQuery;

	private CourierServiceInterface courierService = (CourierServiceInterface) ProxyFactory
			.getProxyInstance(new CourierService());

	ActionContext actionContext = ActionContext.getContext();
	Map<String, Object> session = actionContext.getSession();
	Agent agent = (Agent) session.get("admin");
	
	/**
	 * 
	 * 返回页面
	 * @author Devil Zheng
	 * @created 2015-9-15 下午3:58:16
	 * @return
	 */
	public String returnJSP() {
        return pageName;
    }
	
	/**
	 * 
	 * 获取列表
	 * @author Devil Zheng
	 * @created 2015-9-15 下午3:58:05
	 * @return
	 */
	public String getCourierPage() {
        if (returnType.equals("json")) {
            courierMap = new HashMap<String, Object>();
            courierMap.put("total", courierService.getCourierNumber(agent));
            courierMap.put("rows", courierService.getCouriers(agent, rows, curpage));
            return "jsonSuccess";
        }else{
            return "courierList";
        }
    }
	
	/**
	 * 
	 * 删除
	 * @author Devil Zheng
	 * @created 2015-9-15 下午4:01:50
	 * @return
	 */
    public String deleteCourier(){
        courierMap = new HashMap<String, Object>();
        try {
            courierService.deleteCourier(ids);
            courierMap.put("success", true);
            courierMap.put("msg", "删除成功");
        } catch (Exception e) {
            courierMap.put("success", false);
            courierMap.put("msg", "删除失败"+e.toString());
        }
        return "jsonSuccess";
    }

	public String getAllCourierOfpack() {
		cards = cardDao.getAdminCard();
		return "success";
	}
	
	/**
	 * 
	 * 添加
	 * @author Devil Zheng
	 * @created 2015-9-16 下午3:25:20
	 * @return
	 */
	public String addCourier() {
        Express express = expressBranchDao.getExpressBranch(expressId);
        /*
         * if(courier.getRfid()!=null){
         * cards=cardDao.getByRfid(courier.getRfid()); if(cards.size()!=0){ Card
         * card = cards.get(0); courier.setSernum(card.getSernum());
         * //cardDao.change(card, 1); } }
         */
        courier.setExpress(express);
        courier.setCompany(express.getCompany().getCompanyName());
        courier.setStatus(0);
        courier.setErrorTimes(new BigInteger("0"));
        courier.setErrorRate(new BigDecimal(0));
        // if(courierDao.isCourierExit(courier.getRfid()).size()>0){
        // courier.setStatus(0);
        // courierDao.edit(courier);
        // }else{
        courierDao.save(courier);
        // }
        if ("1".equals(courier.getRole())) {
            express.setCourier(courier);
            expressBranchDao.edit(express);
        }
        return "add";
    }

	/**
	 * 获取所有快递员并分页
	 * 
	 * @return
	 */
	public String getCourierOfPage() {
		if (pageSize == 0) {
			pageSize = 10;
		}
		if (curpage == 0) {
			curpage = 1;
		}
		 if (courierQuery == null) {
		 courierQuery = (CourierQuery) session.get("courierQuery");//
		 //没有清空查询会只显示之前session保存的信息
		 }
		 if ("clearAllTerm".equals(flag)) {
		 session.put("courierQuery", null);
		 courierQuery = null;
		 }
		// if ("list".equals(flag)) {
		// session.put("courierQuery", null);
		// courierQuery = null;
		// }
		courierPage = courierService.getCourierOfPage(curpage, pageSize,
				courierQuery, agent);
		if (courierPage.getList().size() <= 0) { // 判断当前页有没数据
			while (curpage > 1) {
				curpage--;
				courierPage = courierService.getCourierOfPage(curpage,
						pageSize, courierQuery, agent);
				if (courierPage.getList().size() > 0) {
					break;
				}
			}
		}
		session.put("courierQuery", courierQuery);
		couriers = courierPage.getList();
		whriteOffTime();
		if ("list".equals(flag)) {
			return "list"; // 返回列表页
		} else {
			return "ajaxList"; // 返回ajax刷新页
		}
	}

	/**
	 * 通过公司和快递网点查询快递员
	 * 
	 * @return
	 */
	public String searchCourier() {
		if (company == -1) {
			expressBranchs = expressBranchDao.getAgentExpress(agent);
			couriers = courierDao.getByList(null, expressBranchs);
		} else if (company != -1 && expressId == -1) {
			expressBranchs = expressBranchDao.getAgentExpress(agent);
			couriers = courierDao.getByList(companyDao.getCompanyById(company)
					.getCompanyName(), expressBranchs);
		} else {
			couriers = courierDao.searchCourier(expressId);
		}
		if (couriers.size() > 0) {
			whriteOffTime();
		}
		return "success";
	}

	/**
	 * 根据快递员姓名获取快递员列表
	 * 
	 * @return
	 */
	// public String getByCourierName() {
	// expressBranchs = expressBranchDao.getAllExpress(agent);
	// couriers = courierDao.getByName(name,expressBranchs);
	// if(couriers.size()>0){
	// whriteOffTime();
	// }
	// return "list";
	// }

	/**
	 * 写入离线时间
	 */
	public void whriteOffTime() {
		String sql = "select package_store_time from package p where p.package_courier_id = ? order by package_store_time desc";
		String sql1 = "select count(*) from package p where p.package_courier_id = ?";
		long today = new Date().getTime();
		Object object = null;
		for (Courier c : couriers) {
			object = queryDAO.queryUniques(sql, c.getCourierId());
			HibernateSessionFactory.closeSession();
			c.saveNum = (BigInteger) queryDAO.queryUniques(sql1,
					c.getCourierId());
			HibernateSessionFactory.closeSession();
			BigInteger zero = new BigInteger("0");
			if (c.saveNum.compareTo(zero) > 0) {
				c.setErrorRate(new BigDecimal(c.getErrorTimes()).divide(
						new BigDecimal(c.saveNum), 2,
						BigDecimal.ROUND_HALF_DOWN));
			} else {
				c.setErrorRate(new BigDecimal(0));
			}
			if (object == null) {
				c.offLineTime = -1;
			} else {
				c.offLineTime = (int) ((today - ((Timestamp) object).getTime()) / (3600 * 24 * 1000));
			}
			courierDao.edit(c);
		}
	}

	/**
	 * 根据快递员手机号码获取快递员
	 * 
	 * @return
	 */
	// public String getByCourierPhone() {
	// expressBranchs = expressBranchDao.getAllExpress(agent);
	// couriers = courierDao.getByCourierPhone(phoneNum,expressBranchs);
	// if(couriers.size()>0){
	// whriteOffTime();
	// }
	// return "list";
	// }
	/**
	 * 根据rfid获取快递员列表
	 * 
	 * @return
	 */
	// public String getByCourierRfid() {
	// expressBranchs = expressBranchDao.getAllExpress(agent);
	// couriers = courierDao.getByRfid(courierRfid,expressBranchs);
	// if(couriers.size()>0){
	// whriteOffTime();
	// }
	// return "list";
	// }

	/**
	 * 返回rfid
	 * 
	 * @return
	 * @throws Exception
	 */
	public String getRfid() throws Exception {
		cards = cardDao.getSernumCard(sernum);
		if (cards.size() == 1) {
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			out.print(cards.get(0).getRfid());
			out.close();
		} else {
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			out.print("1");
			out.close();
		}
		return null;
	}

	/**
	 * 检测参数是否重复
	 * 
	 * @return
	 * @throws Exception
	 */
	public String checkValue() throws Exception {
		couriers = courierDao.checkValue(flag, value);
		if (couriers.size() == 0) {
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			out.print("0");
			out.close();
		} else {
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			out.print("1");
			out.close();
		}
		return null;
	}

	/**
	 * 检测负责人是否重复
	 * 
	 * @return
	 * @throws Exception
	 */
	public String checkExpress() throws Exception {
		Express express = expressBranchDao.getExpressBranch(expressId);
		if (express.getCourier() == null) {
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			out.print("0");
			out.close();
		} else {
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			out.print("1");
			out.close();
		}
		return null;
	}

	/**
	 * 获取快递员信息 BY ID
	 * 
	 * @return
	 */
	public String getCourierById() {
		courier = courierDao.getCourierById(courierID);
		getBranchAndCompany();
		return "success";
	}

	/**
	 * 获取快递员信息 BY ID(包裹列表)
	 * 
	 * @return
	 */
	public String getPackageCourier() {
		couriers = courierDao.getPackageCourier(courierID);
		courierPage = new PageBean<Courier>(0, 0, 0, couriers);
		if (couriers.size() > 0) {
			whriteOffTime();
			courierPage.setCurpage(1);
			courierPage.setPageSize(1);
			courierPage.setTotal(1);
		}
		return "success";
	}

	/**
	 * 编辑快递员
	 * 
	 * @return
	 */
	public String editCourier() {
		Courier c = courierDao.getCourierById(courierID);
		Express express = expressBranchDao.getExpressBranch(expressId);
		courier.setExpress(express);
		courier.setCompany(express.getCompany().getCompanyName());
		courier.setCourierId(courierID);
		courier.setStatus(c.getStatus());
		courier.setErrorRate(c.getErrorRate());
		courier.setErrorTimes(c.getErrorTimes());
		courierDao.edit(courier);
		if ("1".equals(courier.getRole())) {
			express.setCourier(courier);
			expressBranchDao.edit(express);
		}
		if (express.getCourier()!=null&&express.getCourier().getCourierId() == courierID
				&& "0".equals(courier.getRole())) {
			express.setCourier(null);
			expressBranchDao.edit(express);
		}
		return "success";
	}

	public String signCourier() {
		courier = courierDao.getCourierById(courierID);
		courier.setStatus(Integer.parseInt(flag));
		courierDao.edit(courier);
		return "success";
	}

	/**
	 * 获取快递员的网点和公司
	 * 
	 * @return
	 */
	public String getBranchAndCompany() {
		ActionContext actionContext = ActionContext.getContext();
		Map<String, Object> session = actionContext.getSession();
		Agent admin = (Agent) session.get("admin");
		// cards = cardDao.getAdminCard();
		companies = companyDao.getAllcompany();
		if (company != 0) {
			expressBranchs = expressBranchDao.getCompanyExpressBranch(admin,
					company);
			return "jsonSuccess";
		} else {
			return "success";
		}
	}

	/**
	 * 获取所有快递员
	 * 
	 * @return
	 */
	public String getAll() {
		couriers = courierDao.getAll();
		if (couriers.size() > 0) {
			whriteOffTime();
		}
		return "success";
	}

	public List<Courier> getCouriers() {
		return couriers;
	}

	public void setCouriers(List<Courier> couriers) {
		this.couriers = couriers;
	}

	public Courier getCourier() {
		return courier;
	}

	public void setCourier(Courier courier) {
		this.courier = courier;
	}

	public int getCompany() {
		return company;
	}

	public void setCompany(int company) {
		this.company = company;
	}

	public List<Company> getCompanies() {
		return companies;
	}

	public void setCompanies(List<Company> companies) {
		this.companies = companies;
	}

	public int getCourierID() {
		return courierID;
	}

	public void setCourierID(int courierID) {
		this.courierID = courierID;
	}

	public List<Express> getExpressBranchs() {
		return expressBranchs;
	}

	public void setExpressBranchs(List<Express> expressBranchs) {
		this.expressBranchs = expressBranchs;
	}

	public int getExpressId() {
		return expressId;
	}

	public void setExpressId(int expressId) {
		this.expressId = expressId;
	}

	public List<Branch> getBranchs() {
		return branchs;
	}

	public void setBranchs(List<Branch> branchs) {
		this.branchs = branchs;
	}

	public int getBranch() {
		return branch;
	}

	public void setBranch(int branch) {
		this.branch = branch;
	}

	public List<Card> getCards() {
		return cards;
	}

	public void setCards(List<Card> cards) {
		this.cards = cards;
	}

	public int getCardID() {
		return cardID;
	}

	public void setCardID(int cardID) {
		this.cardID = cardID;
	}

	public String getSernum() {
		return sernum;
	}

	public void setSernum(String sernum) {
		this.sernum = sernum;
	}

	public String getFlag() {
		return flag;
	}

	public void setFlag(String flag) {
		this.flag = flag;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public int getCurpage() {
		return curpage;
	}

	public void setCurpage(int curpage) {
		this.curpage = curpage;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public CourierQuery getCourierQuery() {
		return courierQuery;
	}

	public void setCourierQuery(CourierQuery courierQuery) {
		this.courierQuery = courierQuery;
	}

    public int getRows() {
        return rows;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public String getReturnType() {
        return returnType;
    }

    public void setReturnType(String returnType) {
        this.returnType = returnType;
    }

    public String getPageName() {
        return pageName;
    }

    public void setPageName(String pageName) {
        this.pageName = pageName;
    }

    public Map<String, Object> getCourierMap() {
        return courierMap;
    }

    public void setCourierMap(Map<String, Object> courierMap) {
        this.courierMap = courierMap;
    }
    
    public String getIds() {
        return ids;
    }

    public void setIds(String ids) {
        this.ids = ids;
    }

    @Override
    public Courier getModel() {
        return courier;
    }

}
